<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/10/30
 * Time: 21:42
 */

namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\facade\Log;

// 进行异常处理
class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorcode;

    // 还需要返回出错请求的地址
    public function render(Exception $e)
    {
//        判断是用户出错还是服务器出错
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorcode = $e->errorcode;
        } else {
            if (config('app_debug')) {
                return parent::render($e);
            } else {
                $this->code = 500;
                $this->msg = '服务器出错，但不想告诉你是啥错';
                $this->errorcode = 999;
                $this::WriteLog($e);
            }
        }
        $request = request();
        $arr = [
            'error_code' => $this->errorcode,
            'mag' => $this->msg,
            'request' => $request->url()
        ];
        return json($arr, $this->code);
    }

    private function WriteLog($e)
    {
        Log::init([
            'type' => 'File',
            'path' => '../log',
            'level' => ['error']
        ]);
        Log::write($e->getMessage(), 'error');
    }
}